package com.so.studyonline.controller;

import com.alibaba.fastjson.JSONObject;
import com.so.studyonline.annotation.PassToken;
import com.so.studyonline.mapper.*;
import com.so.studyonline.model.*;
import com.so.studyonline.utils.ResMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("api/pub")
public class InfoSearchNcController {

    private SoConfigMapper soConfigMapper;
    private SoAllContentMapper soAllContentMapper;
    private SoVideoChapterMapper soVideoChapterMapper;
    private SoDiscussMapper soDiscussMapper;
    private SoDiscussReplyMapper soDiscussReplyMapper;
    private SoArticleMapper soArticleMapper;

    @Autowired
    public void setSoConfigMapper(SoConfigMapper soConfigMapper) {
        this.soConfigMapper = soConfigMapper;
    }

    @Autowired
    public void setSoAllContentMapper(SoAllContentMapper soAllContentMapper) {
        this.soAllContentMapper = soAllContentMapper;
    }

    @Autowired
    public void setSoVideoChapterMapper(SoVideoChapterMapper soVideoChapterMapper) {
        this.soVideoChapterMapper = soVideoChapterMapper;
    }

    @Autowired
    public void setSoDiscussMapper(SoDiscussMapper soDiscussMapper) {
        this.soDiscussMapper = soDiscussMapper;
    }

    @Autowired
    public void setSoDiscussReplyMapper(SoDiscussReplyMapper soDiscussReplyMapper) {
        this.soDiscussReplyMapper = soDiscussReplyMapper;
    }

    @Autowired
    public void setSoArticleMapper(SoArticleMapper soArticleMapper) {
        this.soArticleMapper = soArticleMapper;
    }

    /**
     * 登录状态检查
     * @param request 请求
     * @return 需要改造
     */
    @PassToken
    @RequestMapping("login_status")
    @ResponseBody
    public String getLoginStatus(HttpServletRequest request) {
        ResMessage resMessage = new ResMessage();
        Map<String, Object> user = new HashMap<>();
        String userInfo = String.valueOf(request.getSession().getAttribute("userInfo"));
        user.put("id", "null");
        log.info("Session:{}-{}", userInfo, JSONObject.toJSONString(request.getSession()));
        if (!userInfo.equals("null")) {
            String[] users = userInfo.split(",");
            user.put("id", users[0]);
            user.put("userNo", users[1]);
            user.put("userName", users[2]);
            user.put("userType", users[3]);
            user.put("userSex", users[4]);
            user.put("email", users[5]);
            user.put("phone", users[6]);
            user.put("tel", users[7]);
            user.put("userRole", users[8]);
        }

        return resMessage.sysSuccess(user);
    }

    /**
     * @return ｛JSON｝ 列表数据
     * @apiNote getExperience && experience && 首页经验交流区块信息
     */
    @PassToken
    @RequestMapping("experience")
    @ResponseBody
    public String getExperience() {
        ResMessage resMessage = new ResMessage();
        SoConfig soConfig = new SoConfig();
        List<Map<String, Object>> res = new ArrayList<>();
        soConfig.setKey("experience");
        List<SoConfig> listSoConfig = soConfigMapper.findConfig(soConfig);
        for (SoConfig config : listSoConfig) {
            Map<String, Object> resItem = new HashMap<>();
            soConfig = config;
            SoAllContent soAllContent = new SoAllContent();
            soAllContent.setExtrai(soConfig.getValue());
            List<SoAllContent> listSoContent = soAllContentMapper.findExperience(soAllContent);
            resItem.put("list", listSoContent);
            resItem.put("title", soConfig.getName());
            res.add(resItem);
        }
        return resMessage.sysSuccess(res);
    }

    /**
     * @return ｛JSON｝ 返回热门视频列表
     * @apiNote getFireVideo && fireVideo
     */
    @PassToken
    @RequestMapping("fireVideo")
    @ResponseBody
    public String getFireVideo() {
        ResMessage resMessage = new ResMessage();
        SoAllContent soAllContent = new SoAllContent();
        soAllContent.setType("video");
        List<SoAllContent> listSoContent = soAllContentMapper.findFireVideo(soAllContent);
        return resMessage.sysSuccess(listSoContent);
    }

    /**
     * @return ｛JSON｝ 返回视频结果里列表
     * @apiNote getVideoChapter && videoChapter && 获取视频的章节
     */
    @PassToken
    @RequestMapping("videoChapter")
    @ResponseBody
    public String getVideoChapter(@RequestBody JSONObject jsonObject) {
        long id = Integer.parseInt(jsonObject.get("id").toString());
        Integer chapter = Integer.parseInt(jsonObject.get("chapter").toString());
        log.info("videoChapter: {}--{}", id, chapter);
        ResMessage resMessage = new ResMessage();
        SoVideoChapter soVideoChapter = new SoVideoChapter();
        soVideoChapter.setVideoId(id);
        List<SoVideoChapter> listSoVideoChapter = soVideoChapterMapper.findVideoChapterByVideoId(soVideoChapter);
        return resMessage.sysSuccess(listSoVideoChapter);
    }

    /**
     * @param soAllContent 传入搜索数据
     * @return ｛JSON｝ 搜索结果列表
     * @apiNote getAllSearch && allSearch && 页面搜索功能
     */
    @PassToken
    @RequestMapping("allSearch")
    @ResponseBody
    public String getAllSearch(@RequestBody SoAllContent soAllContent) {
        ResMessage resMessage = new ResMessage();
        soAllContent.setPageIndex((soAllContent.getPageIndex() - 1) * soAllContent.getPageNum());
        List<SoAllContent> listSoContent = soAllContentMapper.findAllContentLike(soAllContent);
        int total = soAllContentMapper.findAllContentLikeTotal(soAllContent);
        Map<String, Object> res = new HashMap<>();
        res.put("data", listSoContent);
        res.put("total", total);
        return resMessage.sysSuccess(res);
    }

    /**
     * @param soDiscuss 传入搜索对象
     * @return ｛JSON｝ 返回结果列表
     * @apiNote getDiscuss && discuss && 查询评论信息
     */
    @PassToken
    @RequestMapping("discuss")
    @ResponseBody
    public String getDiscuss(@RequestBody SoDiscuss soDiscuss) {
        log.info(JSONObject.toJSONString(soDiscuss));
        ResMessage resMessage = new ResMessage();
        // topicId 查询评论
        List<SoDiscuss> listSoDiscuss = soDiscussMapper.findDoDiscussAddUserName(soDiscuss);
        // 评论数量为 0
        int row = listSoDiscuss.size();
        if (row == 0) {
            return resMessage.sysSuccess("");
        }
        // 查询对评论的回复
        SoDiscussReply soDiscussReply = new SoDiscussReply();
        soDiscussReply.setTopicId(soDiscuss.getTopicId());
        List<SoDiscussReply> soDiscussReplyList = soDiscussReplyMapper.findSoDiscussReplyAndUserName(soDiscussReply);
        // 整合评论及回复
        List<Object> formDiscuss = new ArrayList<>();
        for (SoDiscuss discuss : listSoDiscuss) {
            Map<String, Object> formDiscussItem = new HashMap<>();
            List<SoDiscussReply> soDiscussReplyItem = new ArrayList<>();
            for (SoDiscussReply discussReply : soDiscussReplyList) {
                if (discussReply.getDiscussId() == discuss.getId()) {
                    soDiscussReplyItem.add(discussReply);
                }
            }
            formDiscussItem.put("out", discuss);
            formDiscussItem.put("inside", soDiscussReplyItem);
            formDiscuss.add(formDiscussItem);
        }

        // 返回信息
        return resMessage.sysSuccess(formDiscuss);
    }

    /**
     * @param soDiscuss 添加文章评论
     * @return 添加结果
     */
    @PassToken
    @RequestMapping("addDiscuss")
    @ResponseBody
    public String addDiscuss(@RequestBody SoDiscuss soDiscuss) {
        // 传入值
        log.info(JSONObject.toJSONString(soDiscuss));
        // 返回信息
        ResMessage resMessage = new ResMessage();
        soDiscuss.setStatus(1);
        soDiscuss.setDiscussTime(new Timestamp(System.currentTimeMillis()));
        // 楼高度+1
        int floor = 0;
        try {
            floor = soDiscussMapper.getFloorMax(soDiscuss.getTopicId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        soDiscuss.setFloor(floor + 1);
        try {
            Integer res = soDiscussMapper.addDiscuss(soDiscuss);
        } catch (Exception e) {
            e.printStackTrace();
            return resMessage.sysError();
        }

        return resMessage.sysSuccess();
    }

    /**
     * 添加评论回复
     * @param soDiscussReply 信息
     * @return 结果
     */
    @PassToken
    @RequestMapping("addDiscussReply")
    @ResponseBody
    public String addDiscussReply(@RequestBody SoDiscussReply soDiscussReply) {
        // 传入值
        log.info(JSONObject.toJSONString(soDiscussReply));
        // 楼高度+1
        int floor = 0;
        try {
            floor = soDiscussReplyMapper.getFloorMax(soDiscussReply);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("楼层高度+1：{}", floor + 1);
        soDiscussReply.setFloor(floor + 1);
        soDiscussReply.setReplyTime(new Timestamp(System.currentTimeMillis()));
        try {
            soDiscussReplyMapper.addDiscussReply(soDiscussReply);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(JSONObject.toJSONString(soDiscussReply));
        return "";
    }

    /**
     * @param soArticle 查询条件
     * @return 返回文章
     * @apiNote articleGet && 查询文章
     */
    @PassToken
    @RequestMapping("article_get")
    @ResponseBody
    public String articleGet(@RequestBody SoArticle soArticle) {
        // 返回信息
        ResMessage resMessage = new ResMessage();
        // 传入数据校验？
        log.info("id:{}---articleId:{}", soArticle.getId(), soArticle.getArticleId());
        // 查询文章概述信息
        SoAllContent soAllContent = soAllContentMapper.findById(soArticle.getArticleId());
        // 文章具体内容
        soArticle = soArticleMapper.getArticleContent(soArticle);
        // 返回信息 返回整合
        Map<String, Object> res = new HashMap<>();
        res.put("id", soAllContent.getId());
        res.put("title", soAllContent.getTitle());
        res.put("article", soArticle.getArticle());
        res.put("content", soAllContent.getContent());
        res.put("author", soAllContent.getAuthor());
        res.put("readTimes", soAllContent.getReadTimes());
        res.put("discussTimes", soAllContent.getDiscussTimes());

        // 信息整合返回
        return resMessage.sysSuccess(res);
    }
}
